package de.dhbw.karlsruhe.picsim.gui.control;

import de.dhbw.karlsruhe.picsim.gui.VisualisationFactory;
import de.dhbw.karlsruhe.picsim.model.PicTime;
import de.dhbw.karlsruhe.picsim.util.impl.LoggingExecutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.concurrent.Executor;

/**
 * Created by IntelliJ IDEA.
 * User: goesen
 * Date: Apr 26, 2010
 * Time: 2:50:17 PM
 */
final class PlayAction extends AbstractAction {
    private static final Log log = LogFactory.getLog(PlayAction.class);
    private final PicTime picModel;
    private final VisualisationFactory visualisationFactory;
    private final JButton pauseButton;
    private final DebugControl debugControl;
    private boolean play;
    private final Executor loggingExecutor;


    public PlayAction(final PicTime picModel, final VisualisationFactory visualisationFactory,
                      final JButton pauseButton, final DebugControl debugControl) {
        super("Play");

        this.picModel = picModel;
        this.visualisationFactory = visualisationFactory;
        this.pauseButton = pauseButton;
        this.debugControl = debugControl;
        loggingExecutor = new LoggingExecutor();
    }

    @Override
    public void actionPerformed(final ActionEvent e) {
        setEnabled(false);
        play = true;
        final PauseAction pauseAction = new PauseAction(this);
        pauseButton.setAction(pauseAction);

        final Runnable worker = getPlayRunnable(pauseAction);
        loggingExecutor.execute(worker);


    }

    private Runnable getPlayRunnable(final PauseAction pauseAction) {
        return new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                while (play) {
                    if (debugControl.shouldStop()) {
                        pauseAction.actionPerformed(null);
                        break;
                    }
                    picModel.circleModel();
                    publish();
                }
                setEnabled(true);
                publish();
                return null;
            }

            @Override
            protected void process(final List<Void> chunks) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        visualisationFactory.rebuild();
                    }
                });

            }
        };
    }

    public boolean isPlay() {
        return play;
    }

    public void setPlay(boolean play) {
        this.play = play;
    }
}
